<?
//ini_set('display_errors', 1); 
//ini_set('log_errors', 1); 
//ini_set('error_log', 'error_log.txt'); 
//error_reporting(E_ALL);
//var_dump($_GET);

$pagename=LA_PIC_UPLOAD;
if (!$admin_area)
	include_once("header_inc.php");
$tplUpload=new TplLoad;
if (!$admin_area)
{
	check_valid_user("");
	include_once("member_header.php");	
}

	
if(isset($_SESSION['transaction_ad_id']) && $_SESSION['transaction_ad_id']!=0)
{
	//Paso anteultimo del flujo de carga de AVISO, la carga de fotos, luego a pagar!!
	$pic_ad_id=$_SESSION['transaction_ad_id'];
	$tplUpload->assign("transaction_ad_id",$_SESSION['transaction_ad_id']);
	$tplUpload->assign("transaction_oid"  ,$_SESSION['transaction_oid']);
	$tplUpload->assign("phpself","upload_file.php");
	//unset($_SESSION['transaction_oid']);	

}else{
	$pic_ad_id=getParam("pic_ad_id","");
	$tplUpload->assign("phpself",$_SERVER['PHP_SELF']);
}
	


if (!$pic_ad_id)
	criticalError(LA_ERROR,LA_ERROR_NO_ID);
$tplUpload->assign("url", "http://$set_url");

$tplUpload->assign("admin_area", "$admin_area");
if (isset($_REQUEST["pic_ad_id"]))
{
	$pic_ad_id = round($_REQUEST["pic_ad_id"]);
	$tplUpload->assign("pic_ad_id",$pic_ad_id);
}

if (getParamInt("mark_as_main",""))
{
	$lMarkId=getParamInt("mark_as_main","");
	if ($lMarkId>0)
	{
		$lSql="update $pic_tbl set main=0 where pic_ad_id=$pic_ad_id";
		$lRes=q($lSql);
		
		$lSql="update $pic_tbl set main=1 where id=$lMarkId";
		$lRes=q($lSql);
	}
}

$arrayOfPinfo=getAds(array("ad_id=$pic_ad_id"),1);
$packageId = $arrayOfPinfo[0]['mv_package_id'];

$lUser=$arrayOfPinfo[0]["ad_owner"];
if($lUser != $_SESSION["valid_user"]){
	die('Invalid Access, please login again');
	
}
$lNumUploaded=getNumberOfImagesUploaded($pic_ad_id); //Cantidad de Imagenes que Tiene Dicho Aviso
$packageInfoArray = getPackageinfo($packageId);
$mainType = $packageInfoArray['mainType'];
$lCountUploadxPackage = $packageInfoArray['pupload'];


/*
 JMR: Nuevo esquema de creditos por paquetes exista o no credito 
 
if ($pic_ad_id)
{
	$result = q("SELECT ad_owner,coalesce(pay_upload,0) as pay_upload,coalesce(a.package_id,0) as package_id FROM $ads_tbl m inner join $AdExtraOptions m2 on m.ad_id=m2.mv_ad_id left join
	mvial_user_credits a on m.ad_owner=a.user_id and a.mainType=$mainType and a.package_id=m2.mv_package_id where m.ad_id=$pic_ad_id ");
	
	$row = mysql_fetch_array($result);
	$ad_owner = $row["ad_owner"];
 	$lPayUpload = $row["pay_upload"];
 	$packageId = $row["package_id"];
  	
 	if ($ad_owner <> $_SESSION["valid_user"] AND !$admin_area)
		criticalError(LA_ERROR,LA_MUSTBEOWNER);
}*/

/*
 * Variable que indica que se utilizarán creditos EXTRA Adquiridos.
 * */
$CreditosExtra = 0;
//JMR: Nuevo esquema de creditos por paquetes exista o no credito
// If payments activated, check ad_has_picture credit

if ($set_payments)
{
/*	//JMR: Nuevo esquema de creditos por paquetes exista o no credito
 * 
 * $lUser=$_SESSION["valid_user"];
	if ($admin_area)
	{
		$res=q("select ad_owner from $ads_tbl where ad_id=" . $pic_ad_id);	
		$row_user=mysql_fetch_array($res);
		$lUser=$row_user["ad_owner"];
	}
	//Obtenemos los datos de los creditos de la persona	 
	if($packageId==0){
		$sql="select pay_upload from mvial_user_credits where user_id=$lUser and mainType=".$mainType." and package_id=0";
	}else{
		$sql="select b.pupload,a.pay_upload from mvial_user_credits a inner join mvial_packages b on b.pid=a.package_id where a.user_id=$lUser and a.mainType=$mainType and a.package_id=$packageId";
	}
	
	$r_user=q($sql);
	$row_user=mysql_fetch_array($r_user);
	$lPayUpload=$row_user["pay_upload"]; //Aquí ponemos el credito del usuario para subir imagenes en dicho aviso
	if($lPayUpload == null){
		$lPayUpload = 0; 
	}
	if($packageId==0){
		$lCountUploadxPackage=$lPayUpload;          //limite dado por el credito en caso de que sea credito de obsequio
	}else{
		$lCountUploadxPackage=$row_user["pupload"]; //limite dado por el tipo de paquete si no es de obsequio 
	}
	$set_image_num_images=$lPayUpload;
*/	
	
	//1. Obtener cantidad de imagenes posibles para el tipo de paquete al que pertenece el aviso
	//2. Obtener número actual de imagenes
	//3. Agregar imagen y restar un punto a los creditos (no importa que quede en negativo, esto se hace más abajo)	
	
	
	
	/* 4.Si llegó al tope de imagenes que podía subir para dicho TIPO de aviso
	 * verificamos si tiene credito EXTRA.
	 * */
	if(($lNumUploaded>=$lCountUploadxPackage) && $mainType!=-1){ //empty($lPayUpload) || 
		$lPayUpload=0;
		//Verificamos los paquetes EXTRA
		$mainType = getExtraMainType($mainType);
		$sqlCheckCredits = "select pay_upload,package_id from mvial_user_credits where user_id=$lUser and mainType=$mainType and pay_upload >0 order by pay_upload DESC limit 1";			
		$res_credits=q($sqlCheckCredits);
		if($rowCredits=mysql_fetch_array($res_credits)){
			if(!empty($rowCredits["package_id"]) && !empty($rowCredits["pay_upload"])){
				$packageId  = $rowCredits["package_id"]; // El package ID que se Actualizara será el de creditos extra
				$lPayUpload = $rowCredits["pay_upload"]; //Cambios la variable de Creditos, ahora se utilizaran los EXTRA								
				$CreditosExtra = 1;
			}
		}
	}
	
}

$size = floor($set_image_limit);
if (getParam("del_id",""))
{
	$lSql="select pic_ad_id from $pic_tbl where id=" . getParamInt("del_id","");
	$lRes=q($lSql);
	$lRow=mysql_fetch_array($lRes);
	if ($lRow["pic_ad_id"]==$pic_ad_id)
	{
		deleteImage(getParamInt("del_id",""));
		$tplUpload->assign("show_form",1);
	}
	else 
	{
		echo "<p>Critical error</p><br />Hack attempt";
	}
}

/*if (getParam("submit",""))
{*/
	if ($CreditosExtra==0 && $lNumUploaded>=$lCountUploadxPackage)
		$lStop=1;	
/*}*/


if (isset($_REQUEST["submit"]) AND !$lStop)
{
	
	$FileArray=$_FILES["photo"];
	$SaveAs=$set_path . "/images/$pic_ad_id";
	$MaxSize="$piclimit";
	$DimensionArray[]=$set_image_size_small;
	$DimensionArray[]=$set_image_size_thumb;
	$DimensionArray[]=$set_image_size_large;
	$ad_id=getParamInt("pic_ad_id","");
	
	$returnValue=uploadImage($FileArray,$SaveAs,$set_image_limit,$DimensionArray,"",$set_image_program);
	
	$lReturnMesg=getErrorMsg($returnValue);
	
	if (is_int($returnValue))
		$tplUpload->assign("error","$lReturnMesg");
	else 
	{
		foreach ($returnValue as $item)
		{
			if ($set_debug)
			{
				echo "Filen $item ble lastet opp!<br>";
				echo "<img src='images/$item'><br>";
				@chmod("images/$item",octdec($set_chmod));
			}
		}
		$sq = "INSERT INTO $pic_tbl (pic_ad_id,filename) VALUES ('$ad_id','$item')";
		$result=q($sq);
		$id = mysql_insert_id();
		
		$sq = "update $ads_tbl set ad_has_picture = 0 where ad_id = $ad_id AND ad_has_picture IS NULL";
		$re = q($sq);
			
		$sq = "update $ads_tbl set ad_has_picture = ad_has_picture + 1 where ad_id = $ad_id";		
		$re = q($sq);
		
		//Actualización de creditos de upload de imagenes
		$sq = "update mvial_user_credits SET pay_upload=pay_upload-1, pay_num_images=pay_num_images-1 where user_id=$lUser and mainType=".$mainType." and package_id=".$packageId;
		$re = q($sq);
		$lPayUpload = $lPayUpload-1;
		//Fin de script de actualizacion
		
		$tplUpload->assign("upload_ok",1);		
	}
}
if($CreditosExtra!=0)
$tplUpload->assign("upload_credits", sprintf(EF_SUBIR_XFOTOS_MAS,$lPayUpload));
$tplUpload->assign("image_upload_size",formatString("<p>".LA_UPLOAD_LIMIT, array("$size")));

/*if ($lNumUploaded>=$set_image_num_images && $CreditosExtra == 0)
	$lStop=1;*/	
	
if($packageId!=0){
	$tplUpload->assign("upload_status", formatString(LA_UPLOAD_STATUS,array("$lNumUploaded","$lCountUploadxPackage")));
}else{
	$tplUpload->assign("upload_status", formatString(LA_UPLOAD_STATUS2,array("$lNumUploaded")));
}


// If less than maxpic has been uploaded, show upload-form
if (!$lStop)
{
	$tplUpload->assign("show_form",1);
}


/**
 * JMR: Dejamos cargar imagenes en el aviso aun cuando no haya creditos, ya que estos se acreditran en el proximo pago de forma
 * 		automatica
 * */
//if($lCountUploadxPackage <= $lNumUploaded && $CreditosExtra == 0 ){
	//$tplUpload->assign("show_form", 0);
//}

if ($pic_ad_id)
{
	$lSQL = "select id,filename,pic_ad_id,main from $pic_tbl where pic_ad_id=$pic_ad_id order by id desc";
	$res_query = q($lSQL);
	$num_ad_has_pictures = mysql_num_rows($res_query);
	$i=0;
	while ($row=mysql_fetch_array($res_query))
	{
		$id = $row["id"];
		$filename = $row["filename"];
		$fArray[$i]["id"] = $id;
		if ($set_image_program==0)
		{
			$lSizeArray=setImageSize($filename,getManualSize("small"),0);
			$fArray[$i]["w"]=$lSizeArray[0];
			$fArray[$i]["h"]=$lSizeArray[1];
		}
		else 
			$filename=ereg_replace("tmb2","tmb1",$filename);
		
		$fArray[$i]["file"] = $filename;
		$fArray[$i]["main"] = $row["main"];
		$i++;
	
	}
	$tplUpload->assign("set_image_program","$set_image_program");
	$tplUpload->assign("image_list", $fArray);
}

// Makes main image for imagegallery
$sql = "select main,id from $pic_tbl where pic_ad_id=$pic_ad_id";
$res_main = q($sql);
$lFound=0;
while ($row_main=mysql_fetch_array($res_main))
{
	$i++;
	if ($row_main["id"] AND !$first)
		$first = $row_main["id"];
		
	if ($row_main["main"]>0)
		$lFound = 1;
}

if ($lFound!=1 && $i>0)
{
	$sql = "update $pic_tbl set main = 1 where id=$first";
	$r_main = q($sql);
}

$tplUpload->assign("id", $pic_ad_id);
$tplUpload->assign("CreditosExtra",$CreditosExtra);
$tplUpload->display("upload_file.tpl");
if (!$admin_area)
{
	include_once("member_footer.php");
	include_once("footer_inc.php"); 
}
?>
